﻿@using System.ComponentModel.DataAnnotations;
@using EmployeeLeaveSystem.Shared.DAO;
@using EmployeeLeaveSystem.Shared.Models;
@inherits LayoutComponentBase
@inject HttpClient _httpClient;
@implements IDisposable
<div class="page">
    <div class="sidebar">
        <NavMenuManager />
    </div>

    <main>
        @if (GobalManager.myInfo == null) {
            <div>您尚未登录！</div>
        }
        <div class="top-row px-4">
            <span style="margin-right:10px"><Avatar Src="@("/ImgsReq/"+GobalManager.myInfo?.Avatar_Name)" /></span>
            <div style="display:flex;flex-direction: column;">
                <div>欢迎您</div>
                <div style="font-weight:bolder">　@GobalManager.myInfo?.Name　</div>
            </div>
        </div>

        <article class="content px-4">
            @Body
        </article>
    </main>
</div>

<Modal Title="登录页面"
       Visible="showModal"
       OnOk="HandleOk"
       OnCancel="HandleCancel">
    <Form Loading="loading" Model="@modal"
          LabelColSpan="8"
          WrapperColSpan="16"
          OnFinish="OnFinished"
          OnFinishFailed="OnFinishFailed"
          @ref="form">
        <FormItem Label="Username">
            <Input @bind-Value="@context.Name" />
        </FormItem>
        <FormItem Label="Password">
            <InputPassword @bind-Value="@context.Password" />
        </FormItem>
    </Form>
</Modal>

@code {
    public StaffInfo modal = new();
    bool showModal = false, loading = false;
    Form<StaffInfo> form;

    protected override void OnInitialized() {
        base.OnInitialized();
    }

    void ShowModal() {
        showModal = true;
    }
    private async void HandleOk(MouseEventArgs e) {
        form.Submit();
    }

    private void HandleCancel(MouseEventArgs e) {
        showModal = false;
    }
    public async void OnFinished() {
        loading = true;
        var res = await _httpClient.PostAsJsonAsync("/Main/Login", modal);
        var netData = await res.Content.ReadFromJsonAsync<NetworkDataLocal<StaffInfo>>();
        loading = false;
        StateHasChanged();
        if (netData != null && netData.data != null) {
            var staffInfo = netData.data as StaffInfo;
            GobalManager.myInfo = staffInfo;
            showModal = false;
            FlushPage();
            GobalManager.FlushPages();
            await App._appHandle.NoticeWithIcon(NotificationType.Success, "登录成功", "您已经登录成功");
        } else {
            await App._appHandle.NoticeWithIcon(NotificationType.Error, "登录失败", netData.errMsg);
        }
    }

    void FlushPage() {
        _ = InvokeAsync(() => { StateHasChanged(); });
    }

    public async void OnFinishFailed() {

    }
    public void Dispose() {
    }
}